import axios from 'axios'
const carModule = {
    namespaced: true,
    state() {
        return {
            goodsList: []
        } //商品数据
    },
    mutations: {
        setGoodList(state, newList) {
            state.goodsList = newList//获取的数据赋值给list
        },
        setIsAll(state, val) {
            state.goodsList.forEach(obj => {
                obj.goods_state = val
            })
            // 2者都可以,这个是放在good组件
            // state.goodsList[val, index].goods_state = val.checked
      },
      subCount(state,index) {
        state.goodsList[index].goods_count--
      },
      addCount(state, index) {
        state.goodsList[index].goods_count++
      },
      setCount(state, obj) {
         state.goodsLit[obj.index].goods_count=obj.num


      // setCount(state, num) {
      //   state.goodsList.forEach(obj => {
      //     obj.goods_count = num
      //   })
      }
        
    },
    actions: {
        async asyncSetGoodList(store) {

            let res = await axios({//相当于全局配置
                url: '/api/cart'
            })

            store.commit('setGoodList', res.data.list)
        }
    },

    getters: {
        totalCount(state) {
            return state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state == true) {
                    sum += obj.goods_count
                }
                return sum
            }, 0)

        },
        totalPrice(state) {
            return state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state == true) {
                    sum += obj.goods_count * obj.goods_price
                }
                return sum
            }, 0)
        },
        isAll(state) {

            return state.goodsList.every((obj) => obj.goods_state === true);
        },
    },
}
export default carModule